package com.le.basic.Sort;

/**
 * 归并排序,分治思想
 */
public class Code_04_MergeSort {

    public static void mergeSort(int[] arr) {
        if (arr == null || arr.length < 2) {
            return;
        }
        mergeSort(arr, 0, arr.length - 1);
    }

    public static void mergeSort(int[] arr, int left, int right) {
        if (left == right) {
            return;
        }
        int mid = (left + right) / 2;
        mergeSort(arr, left, mid);
        mergeSort(arr, mid + 1, right);
        merge(arr, left, mid, right);
    }

    public static void merge(int[] arr, int left, int mid, int right) {
        int[] temp = new int[right - left + 1];
        int i = 0;
        int p1 = left;
        int p2 = mid + 1;
        while (p1 <= mid && p2 <= right) {
            temp[i++] = arr[p1] < arr[p2] ? arr[p1++] : arr[p2++];
        }
        while (p1 <= mid){
            temp[i++] = arr[p1++];
        }
        while (p2 <= right){
            temp[i++] = arr[p2++];
        }
        for (int j = 0; j < temp.length; j++) {
            arr[left + j] = temp[j];
        }
    }

    public static void main(String[] args) {
        int testTime = 500000;
        int maxSize = 100;
        int maxValue = 100;
        boolean succeed = true;
        for (int i = 0; i < testTime; i++) {
            int[] array = Code_01_BubbleSort.generateRandomArray(maxSize, maxValue);
            int[] array1 = Code_01_BubbleSort.copyArray(array);
            int[] array2 = Code_01_BubbleSort.copyArray(array);
            mergeSort(array1);
            Code_01_BubbleSort.comparator(array2);
            if (!Code_01_BubbleSort.isEqual(array1, array2)){
                succeed = false;
                break;
            }
        }
        System.out.println(succeed ? "nice" : "dddd");
//        int[] temp = Code_01_BubbleSort.generateRandomArray(maxSize,maxValue);
//        mergeSort(temp);
//        Code_01_BubbleSort.printArray(temp);
    }
}
